/************************************************************
 * Project Name         [Thinking_In_Java]
 * File Name            [Java_IO_RandomAccessFile2.java]
 * Creation Date        [09-Jul-2014]
 * 
 * Copyright© ge.y.yang@gmail.com All Rights Reserved
 * 
 * Work hard, play harder, think big and keep fit
 ************************************************************/
package pkg_09_io.api;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;

/**
 * 
 * @author 不落的太阳(Sean Yang)
 * @version 1.0
 * @since JDK 6
 * 
 */
public class Java_IO_RandomAccessFile2 {

	public String fileName = "test_raf.txt";

	/**
	 * 记录分数
	 * 
	 * @param breakerName
	 * @param score
	 */
	public void record(String breakerName, int score) {
		// "r" 以只读的方式打开
		// "rw" 打开以便读取和写入
		RandomAccessFile raf = null;

		try {
			raf = new RandomAccessFile(fileName, "rw");
			boolean flag = false;

			// 如果未读到文件结尾
			while (raf.getFilePointer() < raf.length()) {
				String name = raf.readUTF();
				if (breakerName.equals(name)) {
					raf.writeInt(score);
					flag = true;
					break;
				} else {
					// 每个人的记录数为int类型, 大小为4个字节, 一次呢跳过四个字节到下一个人名字之前
					raf.skipBytes(4);
				}
			}

			if (!flag) {
				raf.writeUTF(breakerName);
				raf.writeInt(score);
			}

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (raf != null) {
					raf.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 列出所有记录
	 */
	public void listAllRecords() {
		RandomAccessFile raf = null;

		try {
			raf = new RandomAccessFile(fileName, "r");
			while (raf.getFilePointer() < raf.length()) {
				String name = raf.readUTF();
				int score = raf.readInt();
				System.out.println("名字是: " + name + " 分数是: " + score);
			}

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (raf != null) {
					raf.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Java_IO_RandomAccessFile2 example = new Java_IO_RandomAccessFile2();

		example.record("sean", 100);
		example.record("sean", 80);
		example.record("cc", 120);
		example.record("cc", 200);

		example.listAllRecords();
	}

}
